using System;
using System.Diagnostics;
using GISAzureCore;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace GISWebRole
{
    public class WebRole : RoleEntryPoint
    {
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

                RoleEnvironment.Changed += (sender, arg) =>
                {
                    foreach (var change in arg.Changes)
                    {
                        var configChange = change as RoleEnvironmentConfigurationSettingChange;
                        if (configChange != null)
                        {
                            RoleEnvironment.GetConfigurationSettingValue(
                                configChange.ConfigurationSettingName);
                        }
                    }
                };
            });

            var diag = DiagnosticMonitor.GetDefaultInitialConfiguration();

            diag.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
            diag.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
            diag.WindowsEventLog.DataSources.Add("Application!*");
            diag.WindowsEventLog.DataSources.Add("System!*");
            diag.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
            diag.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diag);

            CloudStorageAccount account = CloudStorageAccount.Parse(
                RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));

            _createBlobContainers(account);
            _createJobQueues(account);
            return base.OnStart();
        }

        private void _createJobQueues(CloudStorageAccount account)
        {
            CloudQueueClient queueClient = account.CreateCloudQueueClient();
            CloudQueue sweepItemsQueue = queueClient.GetQueueReference(DataConstants.SweepItemQueue);
            CloudQueue mergeItemsQueue = queueClient.GetQueueReference(DataConstants.MergeItemQueue);

            sweepItemsQueue.CreateIfNotExist();
            sweepItemsQueue.Clear();
            mergeItemsQueue.CreateIfNotExist();
            mergeItemsQueue.Clear();
        }

        private void _createBlobContainers(CloudStorageAccount account)
        {
            CloudBlobClient blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer mapContainer = blobClient.GetContainerReference(DataConstants.MapContainerBlob);
            CloudBlobContainer sweepItemContainer = blobClient.GetContainerReference(DataConstants.SweepItemContainerBlob);
            mapContainer.CreateIfNotExist();
            sweepItemContainer.CreateIfNotExist();
        }

        private void _createCellTable(CloudStorageAccount account)
        {
            CloudTableClient.CreateTablesFromModel(typeof(CellDataContext),
                                                account.TableEndpoint.AbsoluteUri,
                                                account.Credentials);

            var cellCtxt = new CellDataContext(account.TableEndpoint.ToString(),
                                           account.Credentials);
            cellCtxt.EmptyTable();
        }
    }
}
